// Extensions Made Easy - Copyright 2012 by Jan Van der Haegen - All rights reserved, use for educational purposes only.

using System;
using System.ComponentModel.Composition;
using System.Linq;
using ExtensionsMadeEasy.ClientAPI.Shell;
using Microsoft.LightSwitch.Runtime.Shell;
using Microsoft.VisualStudio.ExtensibilityHosting;

namespace ExtensionsMadeEasy.Presentation.Shells.Components
{
    [Export(typeof(IShell))] 
    [Shell(EasyShell.ShellId)]
    public sealed class EasyShell : IShell
    {
        private bool initialized = false;
        private IShell actualShell;

        private IShell ActualShell
        {
            get
            {
                if (!this.initialized)
                {
                    var allShellExporters = VsExportProviderService.GetExportedValues<IShellExporter>();
                    var shellExporter = allShellExporters.FirstOrDefault();
                    if (shellExporter != null)
                    {
                        this.actualShell = shellExporter.GetShell();
                    }
                    this.initialized = true;
                }
                return this.actualShell;
            }
        }

        #region IShell Members

        public string Name
        {
            get
            {
                return EasyShell.ShellId;
            }
        }

        public Uri ShellUri
        {
            get
            {
                if (this.ActualShell == null)
                {
                    if (VsExportProviderService.GetExportedValues<IShellExporter>().Count() == 0)
                    {
                        throw new NotImplementedException("The selected EasyShell could not find an IShellExporter and does not have a default implementation");
                    }
                    else if (VsExportProviderService.GetExportedValue<IShellExporter>().GetShell() == null)
                    {
                        throw new NotImplementedException("The IShellExporter returned null, and the selected EasyShell does not have a default implementation");
                    }
                    else
                    {
                        throw new NotImplementedException("Unknown error occured");
                    }
                }
                return this.ActualShell.ShellUri;
            }
        }

        #endregion

        #region Constants

        private const string ShellId = "ExtensionsMadeEasy:EasyShell";
        #endregion
    }
}